package com.zjd.association.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zjd.association.common.PageWrapper;
import com.zjd.association.entity.*;
import com.zjd.association.mapper.*;
import com.zjd.association.service.TeamsService;
import com.zjd.association.utils.DateUtils;
import com.zjd.association.utils.UUIDUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 活动信息 服务层实现类
 *
 * @author: zjd
 * @date: 2024-5-22
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class TeamsServiceImpl implements TeamsService {

    private final UsersMapper usersMapper;

    private final TeamTypesMapper teamTypesMapper;

    private final TeamsMapper teamsMapper;

    private final MembersMapper membersMapper;

    private final NoticesMapper noticesMapper;

    private final ActivitiesMapper activitiesDao;

    private final ActiveLogsMapper activeLogsMapper;

    private final ApplyLogsMapper applyLogsMapper;

    private final PayLogsMapper payLogsMapper;

    @Override
    public void add(Teams teams) {
        //检查团长id是否存在
        Users existUser = usersMapper.selectById(teams.getManager());
        if(existUser == null){
            log.error("团长用户不存在 {}", teams);
            throw new RuntimeException("团长用户不存在");
        }

        teamsMapper.insert(teams);
        Members member = new Members();
        member.setId(UUIDUtils.makeIDByCurrent());
        member.setUserId(teams.getManager());
        member.setTeamId(teams.getId());
        member.setCreateTime(DateUtils.getNowDate());

        membersMapper.insert(member);
        Users user = usersMapper.selectById(teams.getManager());
        user.setType(1);

        usersMapper.updateById(user);
    }

    @Override
    public void update(Teams teams) {
        teamsMapper.updateById(teams);
    }

    @Override
    public void delete(Teams teams) {
        QueryWrapper<Notices> qw_notice = new QueryWrapper<>();
        qw_notice.eq("team_id", teams.getId());
        noticesMapper.delete(qw_notice);

        QueryWrapper<PayLogs> qw_pay = new QueryWrapper<>();
        qw_pay.eq("team_id", teams.getId());
        payLogsMapper.delete(qw_pay);

        QueryWrapper<ApplyLogs> qw_apply = new QueryWrapper<>();
        qw_apply.eq("team_id", teams.getId());

        applyLogsMapper.delete(qw_apply);
        QueryWrapper<Members> qw_members = new QueryWrapper<>();
        qw_members.eq("team_id", teams.getId());

        membersMapper.delete(qw_members);

        QueryWrapper<Activities> qw_active = new QueryWrapper<>();
        qw_active.eq("team_id", teams.getId());

        for (Activities activities : activitiesDao.selectList(qw_active)) {
            QueryWrapper<ActiveLogs> qw_active_log = new QueryWrapper<>();
            qw_active_log.eq("active_id", activities.getId());
            activeLogsMapper.delete(qw_active_log);
        }

        activitiesDao.delete(qw_active);
        teamsMapper.deleteById(teams);

        QueryWrapper<Teams> qw_team = new QueryWrapper<>();
        qw_team.eq("manager", teams.getManager());
        if (teamsMapper.selectCount(qw_team) <= 0) {
            Users user = usersMapper.selectById(teams.getManager());
            user.setType(2);
            usersMapper.updateById(user);
        }

    }

    @Override
    public Teams getOne(String id) {
        return teamsMapper.selectById(id);
    }

    /**
     * 获取全部的活动信息列表
     *
     * @return 活动信息
     */
    @Override
    public List<Teams> getAll() {
        QueryWrapper<Teams> qw = new QueryWrapper<>();
        qw.orderByDesc("create_time");
        return teamsMapper.selectList(qw);
    }

    /**
     * 获取指定管理人员相关的活动列表
     *
     * @param manId 指定管理员编号
     * @return 活动信息
     */
    @Override
    public List<Teams> getListByManId(String manId) {
        QueryWrapper<Teams> qw = new QueryWrapper<>();
        qw.eq("manager", manId);
        qw.orderByDesc("create_time");
        return teamsMapper.selectList(qw);
    }

    /**
     * 分页查询活动信息
     *
     * @param pageIndex 当前页码
     * @param pageSize  每页数据量
     * @param teams     模糊查询条件
     * @return 活动信息
     */
    @Override
    public PageWrapper getPageInfo(Long pageIndex, Long pageSize, Teams teams) {
        QueryWrapper<Teams> qw = new QueryWrapper<>();
        if (StrUtil.isNotBlank((teams.getName()))) {
            qw.like("name", teams.getName());
        }

        if (StrUtil.isNotBlank(teams.getTypeId())) {
            qw.eq("type_id", teams.getTypeId());
        }

        if (StrUtil.isNotBlank(teams.getManager())) {
            qw.eq("manager", teams.getManager());
        }

        qw.orderByDesc("create_time");

        Page<Teams> page = teamsMapper.selectPage(new Page<>(pageIndex, pageSize), qw);

        return parsePage(page);
    }

    /**
     * 转化分页查询的结果
     */
    public PageWrapper parsePage(Page<Teams> p) {
        List<Map<String, Object>> resl = new ArrayList<>();

        for (Teams teams : p.getRecords()) {
            Map<String, Object> temp = new HashMap<>();
            temp.put("id", teams.getId());
            temp.put("name", teams.getName());
            temp.put("createTime", teams.getCreateTime());
            temp.put("total", teams.getTotal());

            Users user = usersMapper.selectById(teams.getManager());
            temp.put("manager", teams.getManager());
            temp.put("managerName", user.getName());
            temp.put("managerPhone", user.getPhone());
            temp.put("managerAddress", user.getAddress());

            TeamTypes teamType = teamTypesMapper.selectById(teams.getTypeId());
            temp.put("typeId", teams.getTypeId());
            temp.put("typeName", teamType.getName());
            resl.add(temp);
        }

       return new PageWrapper(p.getCurrent(), p.getSize(), p.getTotal(), resl);
    }

}